"""Authentication routes."""
from flask import request, current_app
from flask_restx import Namespace, Resource, fields
from flask_jwt_extended import create_access_token
import requests
import uuid
from app import db
from app.models.user import User

api = Namespace('auth', description='Authentication operations')

# Models for API documentation
wechat_login_model = api.model('WeChatLogin', {
    'code': fields.String(required=True, description='WeChat login code')
})

login_response_model = api.model('LoginResponse', {
    'access_token': fields.String(description='JWT access token'),
    'user': fields.Raw(description='User information')
})


@api.route('/wechat-login')
class WeChatLogin(Resource):
    """WeChat login endpoint."""
    
    @api.expect(wechat_login_model)
    @api.marshal_with(login_response_model)
    def post(self):
        """Authenticate user with WeChat code.
        
        Validates: Requirements 4.1
        """
        data = request.get_json()
        code = data.get('code')
        
        if not code:
            api.abort(400, 'WeChat code is required')
        
        # Get WeChat config
        app_id = current_app.config.get('WECHAT_APP_ID')
        app_secret = current_app.config.get('WECHAT_APP_SECRET')
        
        if not app_id or not app_secret:
            api.abort(500, 'WeChat configuration is missing')
        
        # Exchange code for openid
        try:
            wechat_url = 'https://api.weixin.qq.com/sns/jscode2session'
            params = {
                'appid': app_id,
                'secret': app_secret,
                'js_code': code,
                'grant_type': 'authorization_code'
            }
            
            response = requests.get(wechat_url, params=params, timeout=10)
            response.raise_for_status()
            result = response.json()
            
            if 'errcode' in result and result['errcode'] != 0:
                api.abort(400, f"WeChat API error: {result.get('errmsg', 'Unknown error')}")
            
            openid = result.get('openid')
            if not openid:
                api.abort(400, 'Failed to get WeChat openid')
            
            # Find or create user
            user = User.query.filter_by(wechat_openid=openid).first()
            
            if not user:
                # Create new user
                user = User(
                    id=str(uuid.uuid4()),
                    wechat_openid=openid,
                    nickname=f'用户{openid[:8]}',
                    preferences={}
                )
                db.session.add(user)
                db.session.commit()
            
            # Generate JWT token
            access_token = create_access_token(identity=user.id)
            
            return {
                'access_token': access_token,
                'user': user.to_dict()
            }, 200
            
        except requests.RequestException as e:
            api.abort(500, f'Failed to communicate with WeChat API: {str(e)}')
